package com.kerpow.KSheet;

import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.kerpow.KSheet.character.CharacterAdapter;
import com.kerpow.KSheet.character.Parser;
import com.kerpow.KSheet.character.CharacterAdapter.PowerSortMethod;
import com.kerpow.KSheet.character.Parser.OnProgressPublishHandler;

public class LoadSheet extends Activity {

	private CharacterAdapter _db; 
	private Long _charID;
	private Cursor _powers;
	private WebView _web;
	private String _path;
	
	private ProgressBar _allProgress;
	private ProgressBar _webpage;
	
	private LoadSheetTask _loader;
	
	private TextView _status;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 
		
		setContentView(R.layout.loadsheet);
		
		setProgressBarVisibility(true);
		
		_web = (WebView)findViewById(R.id.loadsheet_web);
		_web.getSettings().setJavaScriptEnabled(true);
		
		Bundle extras = getIntent().getExtras();
		_path = (savedInstanceState == null) ? null: (String) savedInstanceState.getSerializable("path");
        if(_path == null){
        	_path = extras != null ? extras.getString("path") : null;
        }
        
        _allProgress = (ProgressBar)findViewById(R.id.progress);
        _webpage = (ProgressBar)findViewById(R.id.webpage);
        _status = (TextView)findViewById(R.id.status);
        setResult(RESULT_CANCELED);
	}
	@Override
	protected void onPause() {
		super.onPause();
		_loader.cancel(true);
		_db.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
        _db = new CharacterAdapter(this);
        _db.open();
		
		_loader = new LoadSheetTask();
		_loader.execute();
	}

	private void advanceCursor(){
		
		//String webDetail;
		//boolean loop = true;
		
		if(_powers.isLast() || !_powers.moveToNext()){ //success, move to next
			Log.i("kerpow","charcter #" + _charID + " finished, marking loaded");
			_db.setCharacterLoaded(_charID, _path);
			setResult(RESULT_OK); // no more items! end dis shit
			finish();
		}
		
		/*
		do{
			if(_powers.isLast() || !_powers.moveToNext()){ //success, move to next
				setResult(RESULT_OK); // no more items! end dis shit
				finish();
			}
			
			
			webDetail = _powers.getString(_powers.getColumnIndex(CharacterAdapter.FIELD_POWERS_WEBDETAIL));
			
			if(webDetail.equals(""))
				loop = false;
			
		}while(loop);
		*/
	}
	
private interface MyJSInterface{
		public void sendMessage(String s);
	}
	
	private String formatWebDetail(String s){
		
		s = s.replace("\r", "");
		s = s.replace("\n", "");
		s = s.replace("\t", "");
		
		return s;
	}
		
	private class LoadSheetTask extends AsyncTask<Void,Object,Void>{
		private final int  PROGRESS_POWERS = 0;
		private final int  PROGRESS_WEBLOAD = 1;
		private final int  PROGRESS_DETAIL = 3;
		
		
		@Override
		protected Void doInBackground(Void... params) {
			//load the xml sheet
			Parser p = new Parser(); 
			p.setOnProgressPublishHandler(new OnProgressPublishHandler() {
				@Override
				public void onProgressPublish(int percent) {
					LoadSheetTask.this.publishProgress(PROGRESS_WEBLOAD,percent);
				}
			});
			
			publishProgress(PROGRESS_DETAIL,"Parsing character sheet...");
			
			_charID = _db.createCharacterOrPrepForParse(_path);
			
			p.loadCharacterSheet(_db, _charID, _path); 
			
			_powers = _db.fetchPowers(_charID, PowerSortMethod.Name);
			startManagingCursor(_powers);

			_allProgress.setMax(_powers.getCount());
			_allProgress.setProgress(0);
			
			_web.setWebViewClient(new MyWebViewClient());
			_web.setWebChromeClient(new MyWebViewChromeClient());
			_web.addJavascriptInterface(new MyJSClass(), "android");
			
			if(_powers.moveToFirst())
				loadPower();

			return null;
		}


		@Override
		protected void onProgressUpdate(Object... values) {
			if((Integer)values[0] == PROGRESS_POWERS)
				_allProgress.setProgress((Integer)values[1]);
			else if((Integer)values[0] == PROGRESS_WEBLOAD)
				_webpage.setProgress((Integer)values[1]);
			else if((Integer)values[0] == PROGRESS_DETAIL)
				_status.setText((String)values[1]);
			
				
		}

		private void loadPower(){
			
			
			String url = _powers.getString(_powers.getColumnIndex(CharacterAdapter.FIELD_POWERS_WEBURL));
			String name = _powers.getString(_powers.getColumnIndex(CharacterAdapter.FIELD_POWERS_NAME));
			
			publishProgress(PROGRESS_DETAIL,"Loading " + name + "...");

			publishProgress(PROGRESS_POWERS, _powers.getPosition()+1);
			if(url==null || url.length() < 2){
				advanceCursor();
				loadPower();
			}
			else
				_web.loadUrl(url);
			
			//_web.loadUrl("http://www.wizards.com/dndinsider/compendium/power.aspx?id="+powerID);
			/*
			//load the now current power
			publishProgress(PROGRESS_POWERS, _powers.getPosition());
			_currentPowerName = _powers.getString(_powers.getColumnIndex(CharacterAdapter.FIELD_POWERS_NAME));

		    // Create a new HttpClient and Post Header
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("http://www.wizards.com/dndinsider/compendium/CompendiumSearch.asmx/KeywordSearch");
		    
		    try {
		    	//search the compendium
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		        nameValuePairs.add(new BasicNameValuePair("Keywords", _currentPowerName));
		        nameValuePairs.add(new BasicNameValuePair("NameOnly", "true"));
		        nameValuePairs.add(new BasicNameValuePair("Tab", "Power"));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		        ResponseHandler<String> responseHandler = new BasicResponseHandler();
		        String response = httpclient.execute(httppost, responseHandler);

		        //parse the response and find the power id
		        CompendiumParser parse = new CompendiumParser();
		        String powerID = parse.getPowerID(response, _currentPowerName);
		        if(powerID != null)
		        	_web.loadUrl("http://www.wizards.com/dndinsider/compendium/power.aspx?id="+powerID);
		        else{
		        	advanceCursor();
		        	loadPower(); //there's recursion here but the stack won't go any deeper than 
		        					// the total number of powers, which is under 20
		        }
		    
		    } catch (ClientProtocolException e) {

		    } catch (IOException e) {

		    }
		    */
		}
		
		private class MyWebViewChromeClient extends WebChromeClient{

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				
				publishProgress(PROGRESS_WEBLOAD, newProgress);
			}
			
		}
		
		private class MyWebViewClient extends WebViewClient{
			@Override
			public void onPageFinished(WebView view, String url) {
				//super.onPageFinished(view, url);
				
				/* three types of pages that get loaded
				 * 1. login page - need to sit and wait on the user to send a refresh (todo: hide content we don't care about)
				 * 2. list page - shows the search results of the compendium, we need to find our power name in that list to get
				 * 					its id
				 * 3. power page - store this and move to the next power, if there are no more, finish
				 */
				
				if(url.contains("login")){
					//nothing to do, included to cover all logical states
					publishProgress(PROGRESS_DETAIL,"Waiting on login...");
					_web.pageDown(false);
					//_web.scrollTo(0, 9000);
				}else{
					view.loadUrl("javascript:window.android.sendMessage(document.getElementById('detail')==null ? '': document.getElementById('detail').innerHTML);");
				}
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				/*
				//true means i handled it
				if(url.contains("power.aspx") ||
						url.contains("login.aspx") )
					return super.shouldOverrideUrlLoading(view, url);
				else
					return true;
					*/
				return super.shouldOverrideUrlLoading(view, url);
			}
		}
		
		private class MyJSClass implements MyJSInterface{

			@Override
			public void sendMessage(String s) {
				//store s!!
				try{
					Long powerID = _powers.getLong(_powers.getColumnIndex(CharacterAdapter.FIELD_POWERS_ID));
					//Log.i("kerpow", _powers.getString(_powers.getColumnIndex(CharacterAdapter.FIELD_POWERS_NAME)));
					_db.setPowerWebDetail(powerID, formatWebDetail(s));
								
					advanceCursor();
					loadPower();
				}catch(Exception ex){
					Log.i("kerpow", "EXCEPTION " + ex.getMessage());
				}
			}
			
		}
	}
}
